package com.universal.common.utils;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
public class PageParams {

    // 当前页
    private int pageNo = 1;

    // 每页的数量
    private int pageSize = 10;

    private List<OrderBy> orderBys;

    public PageParams(int pageNo, int pageSize) {
        super();
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }

    public PageParams(int pageNo, int pageSize, OrderBy orderBy) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        orderBy(orderBy);
    }

    public int offset() {
        return (pageNo - 1) * pageSize;
    }

    @Override
    public String toString() {
        return "PageParams [pageNo=" + pageNo + ", pageSize=" + pageSize + "]";
    }

    public PageParams orderBy(OrderBy orderBy) {
        if (orderBy == null) return this;
        if (this.orderBys == null) this.orderBys = new ArrayList<>(2);
        this.orderBys.add(orderBy);
        return this;
    }

    public PageParams orderBys(OrderBy... orderBys) {
        if (this.orderBys == null) this.orderBys = new ArrayList<>(orderBys.length);
        for (OrderBy order : orderBys) {
            if (order != null) this.orderBys.add(order);
        }
        return this;
    }

    public static class OrderBy {

        public static enum OrderType {
            DESC, ASC
        }

        private String field;

        // DESC, ASC
        private String sortType;

        public OrderBy() {
        }

        public OrderBy(String field) {
            this(field, OrderType.ASC);
        }

        public OrderBy(String field, String sortType) {
            this.field = field;
            this.sortType = sortType;
        }

        public OrderBy(String field, OrderType sortType) {
            this.field = field;
            this.sortType = sortType.name();
        }

        /**
         * @return the field
         */
        public String getField() {
            return field;
        }

        /**
         * @param field the field to set
         */
        public void setField(String field) {
            this.field = field;
        }

        /**
         * @return the sortType
         */
        public String getSortType() {
            return sortType;
        }

        /**
         * @param sortType the sortType to set
         */
        public void setSortType(String sortType) {
            this.sortType = sortType;
        }

    }
}
